//
//  WeChatPayTool.m
//  CommunityNannyO2O
//
//  Created by 王禹丞 on 15/10/13.
//  Copyright (c) 2015年 Apple. All rights reserved.
//

#import "WeChatPayTool.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "WXUtil.h"
#import "AccountTool.h"
#import "AppDelegate.h"


@implementation WeChatPayTool


+(void)WeChatWithOrdercode :(NSString *)ordercode prepayid:(NSString *)prepayid orderId:(NSString *)orderid Price :(NSString *)price CityId:(NSString *)cityId noncestr:(NSString *)noncestr Target:(UIViewController *)target{

    
    //将当前事件转化成时间戳
    NSDate *datenow = [NSDate date];
  
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
  
    UInt32 timeStamp =[timeSp intValue];
   
    PayReq *request = [[PayReq alloc]init];
    
    request.openID = WXPayAppID;
    
    request.partnerId = WXPayPartnerId;
    
    request.prepayId= prepayid;
    
    request.package = @"Sign=WXPay";
    
    request.nonceStr= noncestr;
    
    request.timeStamp= timeStamp;
   
    [AccountTool saveOrderId:orderid];

    request.sign =  [self createMD5SingForPay:WXPayAppID partnerid:WXPayPartnerId prepayid:prepayid package:@"Sign=WXPay" noncestr:noncestr timestamp:timeStamp];
    
    
    [WXApi sendReq:request];
}

+(NSString *)createMD5SingForPay:(NSString *)appid_key partnerid:
    (NSString *)partnerid_key prepayid:(NSString *)prepayid_key package:(NSString *)package_key noncestr:(NSString *)noncestr_key timestamp:(UInt32)timestamp_key{
    
    NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
    
    [signParams setObject:appid_key forKey:@"appid"];
    
    [signParams setObject:noncestr_key forKey:@"noncestr"];
    [signParams setObject:package_key forKey:@"package"];
    [signParams setObject:partnerid_key forKey:@"partnerid"];
    [signParams setObject:prepayid_key forKey:@"prepayid"];
    [signParams setObject:[NSString stringWithFormat:@"%u",(unsigned int)timestamp_key] forKey:@"timestamp"];
    
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [signParams allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (   ![[signParams objectForKey:categoryId] isEqualToString:@""]
            && ![[signParams objectForKey:categoryId] isEqualToString:@"sign"]
            && ![[signParams objectForKey:categoryId] isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [signParams objectForKey:categoryId]];
        }
    }
    //添加商户密钥key字段    
    [contentString appendFormat:@"key=%@", WXPayPartnerSecret];

   
    NSString *result = [self md5:contentString];
   
    return result;
}

+(NSString *) md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    //加密规则，因为逗比微信没有出微信支付demo，这里加密规则是参照安卓demo来得
    unsigned char result[16]= "0123456789abcdef";
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    //这里的x是小写则产生的md5也是小写，x是大写则md5是大写，这里只能用大写，逗比微信的大小写验证很逗
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
@end



//@interface SkyAppDelegate : UIResponder <UIApplicationDelegate, WXApiDelegate> //在appDelegate方法中实现WXApiDelegate
//- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
//{
//    
//    // 向微信终端注册appID
//    [WXApi registerApp:WXAppId withDescription:@"weixin demo"];
//}
//
//
//
//#define BASE_URL @"https://api.weixin.qq.com"
//
//@implementation WeChatPayTool
//
//
//+ (void)doGetWithUrl:(NSString *)url path:(NSString *)path params:(NSDictionary *)params callback:(BKHttpCallback) callback
//{
//    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:url]];
//    [httpClient getPath:path
//             parameters:params
//                success:^(AFHTTPRequestOperation *operation, id responseObject){
//                    
//                    NSString *responseJson = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//                    if (responseJson)
//                    {
//                        NSDictionary *result = [responseJson objectFromJSONString];
//                        callback(YES, result);
//                    }
//                    else
//                    {
//                        callback(NO, nil);
//                    }
//                }
//                failure:^(AFHTTPRequestOperation *operation, NSError *error){
//                    callback(NO, nil);
//                }];
//}
//
//+ (void)doPostWithUrl:(NSString *)url path:(NSString *)path params:(NSDictionary *)params callback:(BKHttpCallback)callback
//{
//    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:url]];
//    httpClient.parameterEncoding = AFJSONParameterEncoding;
//    [httpClient postPath:path
//              parameters:params
//                 success:^(AFHTTPRequestOperation *operation, id responseObject){
//                     
//                     NSString *responseJson = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//                     if (responseJson)
//                     {
//                         NSDictionary *result = [responseJson objectFromJSONString];
//                         callback(YES, result);
//                     }
//                     else
//                     {
//                         callback(NO, nil);
//                     }
//                 }
//                 failure:^(AFHTTPRequestOperation *operation, NSError *error){
//                     callback(NO, nil);
//                 }];
//}
//
//+ (void)getImageWithUrl:(NSString *)url callback:(BKHttpCallback)callback
//{
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
//    AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:request];
//    
//    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        UIImage *image = responseObject;
//        NSDictionary *result = @{@"image":image};
//        callback(YES, result);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        callback(NO, nil);
//    }];
//    [requestOperation start];
//}
//
//// 获取token
//- (void)getAccessToken
//{
//    NSString *tokenUrl = @"cgi-bin/token";
//    NSDictionary *param = @{@"grant_type":@"client_credential", @"appid":WXAppId, @"secret":WXAppSecret};
//    [HttpUtil doGetWithUrl:BASE_URL
//                      path:tokenUrl
//                    params:param
//                  callback:^(BOOL isSuccessed, NSDictionary *result){
//                      
//                      NSString *accessToken = result[access_token];
//                      [self getPrepayId:accessToken];
//                  }];
//}
//
//// 生成预支付订单
//- (void)getPrepayId:(NSString *)accessToken
//{
//    NSString *prepayIdUrl = [NSString stringWithFormat:@"pay/genprepay?access_token=%@", accessToken];
//    
//    // 拼接详细的订单数据
//    NSDictionary *postDict = [self getProductArgs];
//    
//    [HttpUtil doPostWithUrl:BASE_URL
//                       path:prepayIdUrl
//                     params:postDict
//                   callback:^(BOOL isSuccessed, NSDictionary *result){
//                       
//                       NSString *prePayId = result[PrePayIdKey];
//                       
//                       // 获取预支付订单id，调用微信支付sdk
//                       if (prePayId)
//                       {
//                           NSLog(@"--- PrePayId: %@", prePayId);
//                           
//                           // 调起微信支付
//                           PayReq *request   = [[PayReq alloc] init];
//                           request.partnerId = WXPartnerId;
//                           request.prepayId  = prePayId;
//                           request.package   = @"Sign=WXPay";
//                           request.nonceStr  = self.nonceStr;
//                           request.timeStamp = [self.timeStamp intValue];
//                           
//                           // 构造参数列表
//                           NSMutableDictionary *params = [NSMutableDictionary dictionary];
//                           [params setObject:WXAppId forKey:@"appid"];
//                           [params setObject:WXAppKey forKey:@"appkey"];
//                           [params setObject:request.nonceStr forKey:@"noncestr"];
//                           [params setObject:request.package forKey:@"package"];
//                           [params setObject:request.partnerId forKey:@"partnerid"];
//                           [params setObject:request.prepayId forKey:@"prepayid"];
//                           [params setObject:self.timeStamp forKey:@"timestamp"];
//                           request.sign = [self genSign:params];
//                           
//                           // 在支付之前，如果应用没有注册到微信，应该先调用 [WXApi registerApp:appId] 将应用注册到微信
//                           [WXApi safeSendReq:request];//发送一个安全请求
//                       }
//                   }];
//}
//
//@end











































